<template>
  <div class="upload_f">
    <el-card class="box-card">
      <el-alert
          title="添加商品"
          type="success"
          center
          show-icon>
      </el-alert>
      <el-steps :active="select_name" align-center class="step" finish-status="success">
        <el-step title="基本信息"></el-step>
        <el-step title="商品描述"></el-step>
        <el-step title="封面图"></el-step>
        <el-step title="轮播图片"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
      <el-tabs v-model="select_name" :tab-position="tabPosition" style="height: 320px;" :before-leave="leave">
        <el-tab-pane label="基本信息" name="1" :before-leave="leave">
          <el-form ref="product" :model="product" label-width="80px" :rules="rules">
            <el-form-item label="商品名称" prop="product_name">
              <el-input v-model="product.product_name"></el-input>
            </el-form-item>

            <el-form-item label="商品价格" prop="product_price">
              <el-input v-model="product.product_price"></el-input>
            </el-form-item>

            <el-form-item label="商品数量" prop="product_num">
              <el-input v-model="product.product_num"></el-input>
            </el-form-item>
            <el-form-item label="商品分类" prop="product_type">
              <el-cascader :options="options" v-model="product.product_type"></el-cascader>
            </el-form-item>
          </el-form>
        </el-tab-pane>
        <el-tab-pane label="商品描述" name="2" :before-leave="leave">
          <el-form ref="product" :model="product" label-width="80px" :rules="rules">
            <el-form-item label="商家描述" prop="product_name">
              <el-input v-model="product.product_desc"></el-input>
            </el-form-item>
            <el-form-item label="物流方式" prop="product_price">
              <el-input v-model="product.product_trans_desc"></el-input>
            </el-form-item>
            <el-form-item label="是否支持退货" prop="product_num">
              <el-input v-model="product.product_can_back"></el-input>
            </el-form-item>
            <el-form-item label="友情提示" prop="product_type">
              <el-input v-model="product.product_danger_desc"></el-input>
            </el-form-item>
          </el-form>
        </el-tab-pane>


        <el-tab-pane label="封面图片" name="3" :before-leave="leave">
          <el-upload
              ref="main_upload"
              action="#"
              list-type="picture-card"
              :file-list="main_img_list"
              :http-request="main_img_up"
              :limit="1"
              :auto-upload="false">
            <i slot="default" class="el-icon-plus"></i>
            <div slot="file" slot-scope="{file}">
              <img
                  class="el-upload-list__item-thumbnail"
                  :src="file.url" alt=""
              >
              <span class="el-upload-list__item-actions">
        <span
            class="el-upload-list__item-preview"
            @click="handlePictureCardPreview(file)"
        >
          <i class="el-icon-zoom-in"></i>
        </span>
        <span
            v-if="!disabled"
            class="el-upload-list__item-delete"
            @click="handleDownload(file)"
        >
          <i class="el-icon-download"></i>
        </span>
        <span
            v-if="!disabled"
            class="el-upload-list__item-delete"
            @click="main_remove(file)"
        >
          <i class="el-icon-delete"></i>
        </span>
      </span>
            </div>
          </el-upload>
          <el-button type="primary" @click="postMainImg">上传</el-button>
          <el-dialog :visible.sync="dialogVisible">
            <img width="100%" :src="dialogImageUrl" alt="">
          </el-dialog>
        </el-tab-pane>


        <el-tab-pane label="轮播图片" name="4" :before-leave="leave">
          <el-upload
              ref="upload"
              :multiple="true"
              action="localhost:80/file/uploadSwiper"
              :on-change="swiperChange"
              :on-remove="swiperRemove"
              :file-list="fileList"
              list-type="picture-card"
              :limit="4"
              :on-exceed="fileNumexceed"
              :http-request="swiperUploadImg"
              :auto-upload="false">
            <i slot="default" class="el-icon-plus"></i>
            <div slot="file" slot-scope="{file}">
              <img
                  class="el-upload-list__item-thumbnail"
                  :src="file.url" alt=""
              >
              <span class="el-upload-list__item-actions">
        <span
            class="el-upload-list__item-preview"
            @click="handlePictureCardPreview(file)"
        >
          <i class="el-icon-zoom-in"></i>
        </span>
        <span
            v-if="!disabled"
            class="el-upload-list__item-delete"
            @click="handleDownload(file)"
        >
          <i class="el-icon-download"></i>
        </span>
        <span
            v-if="!disabled"
            class="el-upload-list__item-delete"
            @click="handleRemove(file)"
        >
          <i class="el-icon-delete"></i>
        </span>
      </span>
            </div>
          </el-upload>
          <el-dialog :visible.sync="dialogVisible">
            <img width="100%" :src="dialogImageUrl" alt="">
          </el-dialog>
          <el-button type="primary" @click="postSwiperImg">上传</el-button>
        </el-tab-pane>


        <el-tab-pane label="完成" name="5">
          <el-empty description=" ">
            <el-button @click="upImg" style="margin-top: -200px;" type="primary">提交</el-button>
          </el-empty>
        </el-tab-pane>
      </el-tabs>
    </el-card>
  </div>
</template>

<script>
export default {
  name: "goodsUpload",
  data() {
    return {
      dialogImageUrl: '',
      dialogVisible: false,
      disabled: false,
      imageUrl: '',
      product: {
        product_name: "",
        product_price: "",
        product_num: "",
        product_type: "",
        product_desc: "",
        product_trans_desc: "",
        product_can_back: "",
        product_danger_desc: "",
        product_main_img: "",
        product_swiper: "",
        shopper_number: "",
        shopper_name: ""
      },
      options: [{
        value: "服装",
        label: "服装"
      }, {
        value: "文具",
        label: "文具"
      }, {
        value: "化妆品",
        label: "化妆品"
      }],

      rules: {
        product_name: [
          {required: true, message: '请输入商品名称', trigger: 'blur'},
        ],
        product_price: [
          {required: true, message: '请输入商品价格', trigger: 'blur'}
        ],
        product_num: [
          {required: true, message: '请输入商品数量', trigger: 'blur'}
        ],
        product_type: [
          {required: true, message: '请输入商品类型', trigger: 'blur'}
        ],
      },
      product_type2: "",
      select_name: "1",
      tabPosition: "left",
      fileList: [],
      swiper_data: "",
      main_data:"",
      main_img_list:[],
    };
  },
  methods: {
    main_remove(_,fileList){
      this.main_img_list=fileList
    },
    postMainImg(){
      if(this.product.product_main_img!==""){
        this.$message.error("已经上传就,请勿重复提交")
        return
      }
      if(this.main_img_list==null){
        this.$message.error("请选择上传图片")
      }
      this.main_data=new FormData()
      this.$refs.main_upload.submit()
      let that = this
      this.$axios({
        method: "POST", url: 'http://localhost:80/file/main_img',
        data: that.main_data,
        contentType: false,
        dataType: 'json',
        headers: {
          "Content-Type": "multipart/form-data",
          "loginToken":"123"
        }
      }).then(res => {
        that.product.product_main_img = res.data.msg
        that.$message.success("图片上传成功")
      })
    },
    main_img_up(file){
      this.main_data.append("file",file.file)
    },
    swiperChange(file) {
      this.fileList.push(file)
    },
    fileNumexceed() {
      console.log(this.fileList)
      this.$message.error('上传文件超过最多的数量!');
    },
    swiperUploadImg(file) {
      this.swiper_data.append('file', file.file)
    },
    postSwiperImg() {
      this.swiper_data = new FormData()
      this.$refs.upload.submit()
      let that = this
      this.$axios({
        method: "POST", url: 'http://localhost:80/file/uploadSwiper',
        data: that.swiper_data,
        contentType: false,
        dataType: 'json',
        headers: {
          "Content-Type": "multipart/form-data"
        }
      }).then(res => {
        console.log(res.data.msg)
        that.product.product_swiper = res.data.msg
        that.$message.success("文件上传成功")
      })
    },
    handlePictureCardPreview(file) {
      console.log(file.url)
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    handleDownload(file) {
      console.log(file);
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg';
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }
      return isJPG && isLt2M;
    },
    upImg() {
      this.product.product_type = "文具"
      console.log(this.product)
      this.product.shopper_number=this.$store.state.usernumber
      this.product.shopper_name=this.$store.state.nickname
      this.$axios.post("http://localhost:80/product/add", this.product).then(res=>{
        if(res.data.code===200){
          this.$message.success("提交成功")
        }else{
          this.$message.error("提交失败")
        }
      })
    },
    uploadImg(params) {
      console.log(params);
      var imgUrl = '';
      let that = this

      // Promise的数据需要用.then得到
      this.getBase64(params.file).then(res => {
        // console.log(res); // res就是base64格式的图片数据
        imgUrl = res
        that.product.img_url = imgUrl
        this.$message({
          message: '文件加载成功',
          type: 'success'
        });
      });
      // 在此axios请求
    },
// 转换格式
    getBase64(file) {
      return new Promise((resolve, reject) => {
        let reader = new FileReader();
        let fileResult = '';
        reader.readAsDataURL(file); //开始转
        reader.onload = function () {
          fileResult = reader.result;
        }; //转 失败
        reader.onerror = function (error) {
          reject(error);
        }; //转 结束  咱就 resolve 出去
        reader.onloadend = function () {
          resolve(fileResult);
        };
      });
    },


    leave() {
      console.log("i am ")
      let item = false
      this.$refs.product.validate((valid) => {
        if (valid) {
          console.log("ok")
          item = true
        } else {
          console.log("false")
          item = false
        }
      })
      return item
    },
    handleRemove(file, fileList) {
      this.fileList = fileList
    }
  }
}
</script>

<style scoped>

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}


.step {
  font-size: 1px !important;
}


.submit_over {
  margin-top: 20px;
  height: 200px;
  position: relative;
}

.middle {
  position: absolute;
  top: 80%;
  left: 50%;
  transform: translateX(-50%);
}
</style>
